package actor

import (
	"sync"

	kadefine "kiwi/actor/define"
	kawork "kiwi/actor/work"
)

var (
	gSystem *kadefine.ActorSystem

	gRootPID         *kadefine.PID
	gRootStartedWg   sync.WaitGroup
	gRootStartedOnce sync.Once
	gRootStoppedWg   sync.WaitGroup
	gRootStoppedOnce sync.Once
)

func receive(ctx kadefine.Context) {
	switch msg := ctx.Message().(type) {
	case *kawork.MessagePostWork:
		msg.Work.Execute(ctx)
		kawork.DestroyMessagePostWork(msg)

	case *kawork.MessageDispatchWork:
		msg.Err = msg.Work.Execute(ctx)
		ctx.Respond(msg)

	case *kadefine.Started:
		gRootStartedOnce.Do(func() {
			gRootStartedWg.Done()
			gRootStoppedWg.Add(1)
		})

	//case *kadefine.Stopping:

	case *kadefine.Stopped:
		gRootStoppedOnce.Do(func() {
			gRootStoppedWg.Done()
		})
	}
}
